﻿using Castle.DynamicProxy;

using TianYuan.Core.Domain.Uow;
using TianYuan.Core.Domain.Uow.Interception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TianYuan.Data.Ef.Dependency
{
    public class UnitOfWorkInterceptor : UnitOfWorkInterceptorabstract
    {
        
        internal readonly IEfUnitOfWork _unitOfWork;

        public UnitOfWorkInterceptor(IEfUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public override void Intercept(IInvocation invocation)
        {
            var disableFiltersAttr = AttributeHelper.GetDisableFiltersAttributeOrNull(invocation.MethodInvocationTarget);
            if (disableFiltersAttr != null)
            {
                List<string> filterNames = disableFiltersAttr.FilterNames.Select(filterName => filterName.ToString()).ToList();
                _unitOfWork.DisableFilters(filterNames.ToArray());
            }
            //MethodInfo method = invocation.Method;
            invocation.Proceed();//先执行方法，下面再自动提交事务，如果有NoUnitOfWork属性则不提交
            //if (Attribute.IsDefined(method, typeof (NoUnitOfWorkAttribute)))
            //{
            //    return;
            //}
            //if (invocation.Method.IsDefined(typeof(NoUnitOfWorkAttribute), true))
            //{
            //    return;
            //}
            var unitOfWorkAttr = AttributeHelper.GetNoUnitOfWorkAttributeOrNull(invocation.MethodInvocationTarget);
            if (unitOfWorkAttr != null)
            {
                return;
            }
            _unitOfWork.Commit();
        }
    }
}
